

var config = require('./config.js')
var http = require('./http.js')
import i18n from '../main.js'
import { router } from '../router'
import {
  PayType,
  AppType
} from '../utils/constant.js'
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const formatHtml = content => {
  if (!content) {
    return
  }
  content = content.replace(/\<p/gi, '<p style="max-width:100% !important;word-wrap:break-word;word-break:break-word;" ')
  content = content.replace(/\<img/gi, '<img style="max-width:100% !important;height:auto !important;margin:0;display:flex;" ')
  content = content.replace(/style="/gi, 'style="max-width:100% !important;table-layout:fixed;word-wrap:break-word;word-break:break-word;')
  content = content.replace(/\<table/gi, '<table style="table-layout:fixed;word-wrap:break-word;word-break:break-word;" ')
  // content = content.replace(/\<td/gi,'<td cellspacing="0" cellpadding="0" border="0" style="display:block;vertical-align:top;margin: 0px; padding: 0px; border: 0px;outline-width:0px;"');
  content = content.replace(/\<td/gi, '<td cellspacing="0" cellpadding="0" style="border-width:1px; border-style:solid; border-color:#666; margin: 0px; padding: 0px;"')
  content = content.replace(/width=/gi, 'sss=')
  content = content.replace(/height=/gi, 'sss=')
  content = content.replace(/ \/\>/gi, ' style="max-width:100% !important;height:auto !important;margin:0;display:block;" \/\>')
  return content
}

const endOfStartTime = (startTime, endTime) => {
  let result = {
    day: '00',
    hou: '00',
    min: '00',
    sec: '00',
    signs: 0
  }

  if (endTime - startTime > 0) {
    const time = (endTime - startTime) / 1000 // 获取天、时、分、秒
    const day = parseInt(time / (60 * 60 * 24))
    const hou = parseInt(time % (60 * 60 * 24) / 3600)
    const min = parseInt(time % (60 * 60 * 24) % 3600 / 60)
    const sec = parseInt(time % (60 * 60 * 24) % 3600 % 60)
    result = {
      day: `${timeFormat(day)}`,
      hou: `${timeFormat(hou)}`,
      min: `${timeFormat(min)}`,
      sec: `${timeFormat(sec)}`,
      signs: 1
    }
  }

  return result
} // 小于10的格式化函数

const timeFormat = times => {
  return times < 10 ? '0' + times : times
}

const dateToTimestamp = dateStr => {
  if (!dateStr) {
    return ''
  }

  const newDataStr = dateStr.replace(/\.|\-/g, '/')
  const date = new Date(newDataStr)
  const timestamp = date.getTime()
  return timestamp
}

/**
 * 初始化支付类型
 */
const initPayType = () => {
  const appType = uni.getStorageSync('appType')
  const payTypeInfo = {
    payType: PayType.ALIPAY_H5,
    payTypeStr: 'aliPay'
  }
  // #ifdef H5
  if (appType === AppType.MP) {
    // 如果是微信环境打开,使用公众号支付
    payTypeInfo.payType = PayType.WECHATPAY_MP
    payTypeInfo.payTypeStr = 'wechatPay'
  }
  // #endif

  // #ifdef APP-PLUS
  payTypeInfo.payType = PayType.ALIPAY_APP
  payTypeInfo.payTypeStr = 'aliPay'
  // #endif

  // #ifdef MP-WEIXIN
  payTypeInfo.payType = PayType.WECHATPAY
  payTypeInfo.payTypeStr = 'wechatPay'
  // #endif
  return payTypeInfo
}

// 检查是否授权
const checkAuthInfo = fn => {
  uni.hideLoading()
  // eslint-disable-next-line no-undef
  const pages = getCurrentPages()
  if (uni.getStorageSync('token')) {
    fn()
    return
  }
  if (pages[0] && pages[0].route === 'pages/cart/cart') {
    return
  }
  // 设置登录后的跳转地址
  setRouteUrlAfterLogin()

  if (uni.getStorageSync('tempUidB2c')) {
    uni.navigateTo({
      url: '/pages/register/register'
    })
  } else { // 没有tempUid
    uni.navigateTo({
      url: '/pages/account-login/account-login'
    })
  }
}

/**
 * 手机号正则校验
 */
const checkPhoneNumber = (phoneNumber) => {
  var regexp = /^[1][0-9]{10}$/
  return regexp.test(phoneNumber)
}

/**
 * 用户名正则校验
 */
const checkUserName = (userName) => {
  var regexp = /^([a-zA-Z0-9_]{4,16})$/
  return regexp.test(userName)
}
/**
 * 获取链接上的参数
 */
const getUrlKey = (name) => {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || ['', ''])[1]
    .replace(/\+/g, '%20')) || null
}

/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
const throttle = (fn, t) => {
  let last
  let timer
  const interval = t || 500
  return function() {
    const args = arguments
    const now = +new Date()
    if (last && now - last < interval) {
      clearTimeout(timer)
      timer = setTimeout(() => {
        last = now
        fn.apply(this, args)
      }, interval)
    } else {
      last = now
      fn.apply(this, args)
    }
  }
}

/**
 * 记录页面点击次数
 */
const tapLog = (visitType, orderNumbers, isPayRes, prodNum) => {
  // 更新会话时间
  uni.setStorageSync('sessionTimeStamp', new Date().getTime())
  var flowAnalysisLogDto = uni.getStorageSync('flowAnalysisLogDto')
  flowAnalysisLogDto.visitType = visitType || 3
  flowAnalysisLogDto.nums = prodNum || undefined
  // 支付页面单独处理
  if (orderNumbers) {
    visitType = 1
    flowAnalysisLogDto.step = flowAnalysisLogDto.step + 1
    flowAnalysisLogDto.orderNumbers = orderNumbers
    flowAnalysisLogDto.pageId = !isPayRes ? 10 : 11
  }
  http.saveLog(flowAnalysisLogDto, visitType)
}

/**
 * 获取唯一值
 */
const getUuid = () => {
  var s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'

  var uuid = s.join('')
  return uuid
}

/**
 * 时间戳转化为年 月 日 时 分 秒
 * number: 传入时间戳
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致
*/
const tsToDate = (number, format) => {
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
  var returnArr = []
  var date = new Date(number)
  returnArr.push(date.getFullYear())
  returnArr.push(date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1)
  returnArr.push(date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
  returnArr.push(date.getHours() < 10 ? '0' + date.getHours() : date.getHours())
  returnArr.push(date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
  returnArr.push(date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i])
  }
  return format
}

/**
 * tabbar国际化
 */
const transTabbar = () => {
  uni.setTabBarItem({
    index: 0,
    text: i18n.t('index.homepage')
  })
  uni.setTabBarItem({
    index: 1,
    text: i18n.t('index.classification')
  })
  uni.setTabBarItem({
    index: 2,
    text: i18n.t('index.cart')
  })
  uni.setTabBarItem({
    index: 3,
    text: i18n.t('index.myself')
  })
}

/**
 * 移除购物车Tabbar的数字
 */
const removeTabBadge = () => {
  let pl = ''
  // #ifdef MP-WEIXIN
  pl = 'mp'
  // #endif
  uni.removeTabBarBadge({
    index: pl == 'mp' ? 3 : 2
  })
}
// 防抖 防止表单重复提交
const debounce = (func, wait) => {
  let timer
  return function() {
    const args = arguments // arguments中存着e

    if (timer) clearTimeout(timer)

    timer = setTimeout(() => {
      func.apply(this, args)
    }, wait)
  }
}

/**
 * 用户密码校验
 * @returns {Boolean}
 */
const checkPassword = (password) => {
  const regexp = new RegExp('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,20}$')
  return regexp.test(password)
}

/**
 * 微信环境统一登录方法 (公众号 & 小程序)
 *  * @param {Boolean} showBindTips 是否要展示绑定提示: 当用户主动点击登录时，显示提示
 */
const weChatLogin = (showBindTips) => {
  const appType = uni.getStorageSync('appType')
  if (appType !== AppType.MP && appType !== AppType.MINI) {
    return
  }
  if (getApp().globalData.isLanding) return
  // 改变全局中登录
  const globalData = getApp().globalData
  globalData.isLanding = true
  if (appType === AppType.MINI) {
    // 微信小程序
    // 请求微信接口获取 code
    wx.login({
      success: (res) => {
        // 用code 请求登录
        loginByCode(res.code, showBindTips)
      }
    })
    return
  }
  if (appType === AppType.MP) {
    const tempuid = uni.getStorageSync('tempUidB2c')
    const token = uni.getStorageSync('token')
    // 微信公众号
    if (!tempuid && !token) {
      const code = getUrlKey('code')
      if (!code) {
        globalData.isLanding = false
        http.mpAuthLogin(config.domainAddress, true)
        return
      }
      // 先请求微信公众号登录接口
      loginByCode(code, showBindTips)
    } else {
      globalData.isLanding = false
    }
  }
}

/**
 * 通过微信返回的code登录
 * @param {String} code 请求微信返回的 code
 */
const loginByCode = (code, showBindTips) => {
  const params = {
    login: true,
    url: uni.getStorageSync('appType') === AppType.MINI ? '/social/ma' : '/social/mp',
    method: 'POST',
    data: code,
    callBack: res => {
      loginSuccess(res)
    },
    errCallBack: errRes => {
      // A04001 社交账号未绑定，保存 tempUid
      if (errRes.code === 'A04001') {
        uni.setStorageSync('tempUidB2c', errRes.data)
      }
      // 还原全局 正在登录状态
      getApp().globalData.isLanding = false
      while (getApp().globalData.requestQueue.length) {
        http.request(getApp().globalData.requestQueue.pop())
        getApp().globalData.currentReqCounts--
      }
      console.log('social login ErrRes:', errRes)
    }
  }
  http.request(params)
}

/**
 * 登录成功
 * @param {Object} loginRes 登录成功返回的数据
 * @param {Boolean} isRefreshToken 该次登录是否为刷新token;
 */
const loginSuccess = (loginRes, isRefreshToken) => {
  uni.setStorageSync('isPrivacy', 1)
  uni.setStorageSync('hadLogin', true)
  uni.setStorageSync('token', loginRes.accessToken)
  uni.setStorageSync('loginResult', loginRes) // 保存整个登录数据
  const expiresTimeStamp = loginRes.expiresIn * 1000 / 2 + new Date().getTime()
  // 缓存token的过期时间
  uni.setStorageSync('expiresTimeStamp', expiresTimeStamp)

  // 还原全局 正在登录状态
  getApp().globalData.isLanding = false
  while (getApp().globalData.requestQueue.length) {
    http.request(getApp().globalData.requestQueue.pop())
  }
  // 请求购物车数量
  http.getCartCount()

  const routeUrlAfterLogin = uni.getStorageSync('routeUrlAfterLogin')
  const pages = getCurrentPages()
  const nowRoute = pages[pages.length - 1].route
  // 若为刷新token的登录
  if (isRefreshToken) {
    // 在登录页面登录时
    if (nowRoute === 'pages/account-login/account-login') {
      uni.reLaunch({
        url: '/pages/index/index'
      })
    }
    return
  }

  if (pages.length === 1) {
    uni.reLaunch({
      url: routeUrlAfterLogin || '/pages/index/index'
    })
    uni.removeStorageSync('routeUrlAfterLogin')
    return
  }
  const prevPage = pages[pages.length - 2]
  if (!prevPage) {
    router.pushTab('/pages/index/index')
    return
  }
  // 判断上一页面是否为tabbar页面 (首页和分类页无需登录接口)
  const isTabbar = prevPage.route === 'pages/user/user' || prevPage.route === 'pages/basket/basket'
  if (isTabbar) {
    router.pushTab('/' + prevPage.route)
  } else {
    // 非tabbar页面
    let backDelata = 0
    pages.forEach((page, index) => {
      if (page.$page.fullPath === routeUrlAfterLogin) {
        backDelata = pages.length - index - 1
      }
    })
    if (backDelata) {
      uni.navigateBack({
        delta: backDelata
      })
    } else {
      router.pushTab('/pages/index/index')
    }
  }
}

/**
 * 刷新token
 */
const refreshToken = (params) => {
  const refreshToken = uni.getStorageSync('loginResult').refreshToken
  const expiresTimeStamp = uni.getStorageSync('expiresTimeStamp')
  if (!(refreshToken && expiresTimeStamp && expiresTimeStamp < new Date().getTime())) {
    return params
  }
  getApp().globalData.isLanding = true
  getApp().globalData.requestQueue.push(params)
  return {
    url: '/token/refresh',
    method: 'POST',
    login: true,
    isRefreshing: true,
    dontTrunLogin: true,
    data: {
      refreshToken
    },
    callBack: res => {
      getApp().globalData.isLanding = false
      loginSuccess(res, true)
    },
    errCallBack: errMsg => {
      uni.hideLoading()
      // 清除refreshToken 过期时间
      uni.removeStorageSync('expiresTimeStamp')
      uni.removeStorageSync('tempUidB2c')
      uni.removeStorageSync('loginResult')
      uni.removeStorageSync('token')
      uni.removeStorageSync('hadBindUser')
      uni.removeStorageSync('code')
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('expiresTimeStamp')

      // 还原全局 正在登录状态
      getApp().globalData.isLanding = false
      while (getApp().globalData.requestQueue.length) {
        const queueParam = getApp().globalData.requestQueue.pop()
        http.request(queueParam)
      }
      // 请求微信环境登录
      weChatLogin()
    }
  }
}

/**
 * 获取uni-app相关配置
 */
const getUniWebConfig = () => {
  var params = {
    url: '/webConfig/getUniWebConfig',
    method: 'GET',
    callBack: res => {
      uni.setStorageSync('uniLoginLogoImg', res.uniLoginLogoImg || '')
      uni.setStorageSync('uniTitleContentCn', res.uniTitleContentCn || null)
    }
  }
  http.request(params)
}

/**
 * 设置登录后的跳转地址
 */
const setRouteUrlAfterLogin = () => {
  const pages = getCurrentPages()
  // 登录后的回跳地址
  if (pages[pages.length - 1].route.indexOf('register') === -1 && pages[pages.length - 1].route.indexOf('account-login') === -1) {
    uni.setStorageSync('routeUrlAfterLogin', pages[pages.length - 1].$page.fullPath)
  }
}

/**
 * 选择的图片是否小于2M
 * @param {Array} tempFiles 上传的图片临时文件数组
 * @return {Boolean} 是否小于2M
 */
const lessThan2M = (tempFiles) => {
  let flag = true
  for (let i = 0; i < tempFiles.length; i++) {
    const file = tempFiles[i]
    if (file.size > 1024 * 1024 * 2) {
      uni.showToast({
        title: i18n.t('index.lessThan2M'),
        duration: 2000,
        icon: 'none'
      })
      flag = false
      break
    }
  }
  return flag
}

/**
 * 根据地址返回省市区
 * @param {String} address 地址
 * @param {String} name 地名
 * @return {Array} 省市区的信息
 */
const area = async(address, name) => {
  if (!address) return
  const areaInfoArr = []
  let province, city, area // 名字
  let provinceIndex, cityIndex, areaIndex // 所处的索引
  let provinceId, cityId, areaId // areaId
  // 特殊的区域
  if (name.includes('苏滁现代产业园')) {
    province = '安徽省'
    city = '苏滁市'
    area = '苏滁现代产业园'
  } else if (name.includes('保定白沟新城')) {
    province = '河北省'
    city = '保定市'
    area = '保定白沟新城'
  } else if (name.includes('中沙群岛')) {
    province = '海南省'
    city = '三沙市'
    area = '中沙群岛的岛礁及其海域'
  } else {
    const provSuffix = ['省', '自治区', '黑龙江', '北京市', '天津市', '上海市']
    const citySuffix = ['市', '地区', '自治州', '盟']
    const areaSuffix = ['区', '市', '县', '群岛']
    let aIndex = 0
    const common = (arr) => {
      aIndex = 0
      for (let i = 0; i < arr.length; i++) {
        const index = address.indexOf(arr[i])
        if (index !== -1) {
          aIndex = index + arr[i].length
          break
        }
      }
    }
    common(provSuffix)
    if (aIndex === 0) return
    province = address.substring(0, aIndex)
    address = address.substring(aIndex)
    // 直辖市
    if (province === '北京市' || province === '天津市' || province === '上海市') {
      common(areaSuffix)
      if (aIndex === 0) return
      area = address.substring(0, aIndex)
      city = area.includes('县') ? '县' : '市辖区'
    } else {
      common(citySuffix)
      if (aIndex === 0) return
      city = address.substring(0, aIndex)
      address = address.substring(aIndex)
      common(areaSuffix)
      if (aIndex === 0) return
      area = address.substring(0, aIndex)
    }
  }
  const getListByPid = (pid) => {
    return new Promise((resolve, reject) => {
      const params = {
        url: '/p/area/listByPid',
        method: 'GET',
        data: {
          pid
        },
        callBack: (res) => {
          resolve(res)
        }
      }
      http.request(params)
    })
  }
  // 省
  const res1 = await getListByPid(0)
  for (let i = 0; i < res1.length; i++) {
    if (province === res1[i].areaName) {
      provinceIndex = i
      provinceId = res1[i].areaId
      break
    }
  }
  // 市
  const res2 = await getListByPid(provinceId)
  for (let i = 0; i < res2.length; i++) {
    if (city === res2[i].areaName) {
      cityIndex = i
      cityId = res2[i].areaId
      break
    }
  }
  // 区
  const res3 = await getListByPid(cityId)
  for (let i = 0; i < res3.length; i++) {
    if (area === res3[i].areaName) {
      areaIndex = i
      areaId = res3[i].areaId
      break
    }
  }
  areaInfoArr.push({
    name: province,
    index: provinceIndex,
    areaId: provinceId
  })
  areaInfoArr.push({
    name: city,
    index: cityIndex,
    areaId: cityId
  })
  areaInfoArr.push({
    name: area,
    index: areaIndex,
    areaId
  })
  areaInfoArr.push(res1) // 省数组
  areaInfoArr.push(res2) // 市数组
  areaInfoArr.push(res3) // 区数组
  return areaInfoArr
}

module.exports = {
  getUrlKey: getUrlKey,
  dateToTimestamp: dateToTimestamp,
  formatTime: formatTime,
  formatHtml: formatHtml,
  endOfStartTime: endOfStartTime,
  checkAuthInfo: checkAuthInfo,
  checkPhoneNumber: checkPhoneNumber,
  checkUserName: checkUserName,
  throttle: throttle,
  tapLog: tapLog,
  getUuid: getUuid,
  tsToDate: tsToDate,
  transTabbar: transTabbar,
  removeTabBadge: removeTabBadge,
  initPayType: initPayType,
  debounce: debounce,
  weChatLogin: weChatLogin,
  loginSuccess: loginSuccess,
  refreshToken: refreshToken,
  checkPassword: checkPassword,
  getUniWebConfig: getUniWebConfig,
  setRouteUrlAfterLogin,
  lessThan2M,
  area
}
